package com.sport.facilities.booking.system;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.R.drawable;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.sport.facilities.booking.db.DatabaseHelper;
import com.sport.facilities.booking.system.httptask.CancelBookingPageTask;
import com.sport.facilities.booking.system.httptask.CancelBookingResultTask;
import com.sport.facilities.booking.system.httptask.OnTaskCompleted;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.BookingRequestModel;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.YesAction;



public class CancelBookingActivity extends Activity {
	private static final String TAG = "CancelBookingActivity";
	final Context context = this;
	final CancelBookingActivity cancelActivity = this;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cancel_booking);
		//fnaddtesttodbandalarm();

	}

	@Override
	public void onResume() {
		super.onResume();
		fnLoadCancelBookData();
	}

	protected void fnSetCancelBooking(List<Booking> bookingList) {
		if (bookingList.size() > 0) {

			TableLayout tbl = (TableLayout) findViewById(R.id.cancel_booking_table);
			TextView[][] tvs;
			TableRow[] tbrs;
			tvs = new TextView[bookingList.size()][6];
			tbrs = new TableRow[bookingList.size() + 1];
			int count = bookingList.size();
			for (int i = 0; i < count; i++) {
				Booking bkk = (Booking) bookingList.get(i);
				tbrs[i] = new TableRow(this);
				tbrs[i].setTag(bkk.getId());
				
				if (i % 2 == 0) {
					tbrs[i].setBackgroundResource(R.color.color_white);
				} else {
					tbrs[i].setBackgroundResource(R.color.color_normal_grey);
				}
				tbrs[i].setBackgroundResource(drawable.list_selector_background);

				final CancelBookingActivity cbmActivity = this;

				tbrs[i].setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (v instanceof TableRow) {
							TableRow row = (TableRow) v;
							TextView cancelid = (TextView) row.getChildAt(5);
							TextView activity = (TextView) row.getChildAt(4);
							TextView date = (TextView) row.getChildAt(0);
							TextView time = (TextView) row.getChildAt(1);
							TextView centre = (TextView) row.getChildAt(2);
							TextView court = (TextView) row.getChildAt(3);
							// Log.d(TAG, "2. Clicked " + child.getText());
							// Log.d(TAG, "2. Clicked " + cancelid.getText());


							final Booking bkdetail = new Booking();							
							bkdetail.setActivity(((String) activity.getText()).replaceAll("\\s+", " "));
							bkdetail.setDate((String)date.getText());
							bkdetail.setTime((String)time.getText());
							bkdetail.setCentre((String)centre.getText());
							bkdetail.setCourt((String)court.getText());
							bkdetail.setBkType("Cancel Booking");
							
							
							final BookingRequestModel bkmodel = new BookingRequestModel();
							bkmodel.setId((String) cancelid.getText());
							Log.d(TAG, "Remove Record with Cancel ID : "
									+ bkmodel.getId() + "?");

							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									context);

							// set title
							alertDialogBuilder.setTitle("Cancel Booking");

							// set dialog message
							alertDialogBuilder
									.setMessage(
											"Date:      " + date.getText()
													+ "\n" + "Time:     "
													+ ((String) time.getText()).replaceAll("\n to \n", "-") + "\n"
													+ "Centre:   "
													+ centre.getText() + "\n"
													+ "Activity: "
													+ ((String) activity.getText()).replaceAll("\n", " ") + "\n")

									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {

													OnTaskCompleted completeAction2 = new OnTaskCompleted() {

														public void onTaskCompleted(
																Object result) {

															removetbr();

															
															
															// alert box success
															DialogHelper
																	.getOkAlertDialog(
																			cbmActivity,
																			"Cancel Booking",
																			"Cancel successfully.")
																	.show();
															
															//add to database
															fnaddactivitytodb(bkdetail);
															fnRemoveBKfromAlarm(bkdetail);
															//alert go facebook sharing box	
															fngofacebook(bkdetail);
															
															onResume();
														}

														public void onTaskFailed(
																String errMessage) {
															fnfailtocancel();
														}

													};

													CancelBookingResultTask cbpTask = new CancelBookingResultTask(
															context,
															completeAction2);
													cbpTask.fnCancelBook(bkmodel);

												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													// if this button is
													// clicked, just close
													// the dialog box and do
													// nothing
													dialog.cancel();
												}
											});
							// create alert dialog
							AlertDialog alertDialog = alertDialogBuilder
									.create();
							// show it
							alertDialog.show();

						}

					}
				});
				tvs[i][1] = new TextView(this);
				tvs[i][1].setTag("date" + i);// setting tag with index i
				tvs[i][1].setText(bkk.getDate().substring(0, bkk.getDate().length() - 5));
				tvs[i][1].setTextSize(12);
				tvs[i][1].setWidth(40);
				//tvs[i][1].setBackgroundColor(Color.BLUE);
				tvs[i][1].setHeight(120);
				tvs[i][1].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].addView(tvs[i][0]);
				tbrs[i].addView(tvs[i][1]);

				tvs[i][2] = new TextView(this);
				tvs[i][2].setTag("time" + i);// setting tag with index i
				tvs[i][2].setText(bkk.getTime());
				tvs[i][2].setTextSize(12);
				tvs[i][2].setWidth(160);
				tvs[i][2].setHeight(120);
				//tvs[i][2].setBackgroundColor(Color.GREEN);
				tvs[i][2].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].setPadding(0, 20, 0, 0);
				// rowspan[i].addView(tvs[i][1]);

				tbrs[i].addView(tvs[i][2]);

				// tbrs[i].addView(rowspan[i]);

				tvs[i][3] = new TextView(this);
				tvs[i][3].setTag("centre" + i);// setting tag with index i
				tvs[i][3].setText(bkk.getCentre());
				tvs[i][3].setTextSize(12);
				tvs[i][3].setWidth(190);
				tvs[i][3].setHeight(120);
				//tvs[i][3].setBackgroundColor(Color.BLUE);
				tvs[i][3].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][3].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][3]);

				tvs[i][4] = new TextView(this);
				tvs[i][4].setTag("court" + i);// setting tag with index i
				tvs[i][4].setText(bkk.getCourt());
				tvs[i][4].setTextSize(12);
				tvs[i][4].setWidth(55);
				tvs[i][4].setHeight(120);
				//tvs[i][4].setBackgroundColor(Color.GREEN);
				tvs[i][4].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][4].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][4]);

				tvs[i][5] = new TextView(this);
				tvs[i][5].setTag("activity" + i);// setting tag with index i
				String tmpActivity = bkk.getActivity().replaceAll("  ", "\n");
				tmpActivity = tmpActivity.replaceAll(" ", "\n");
				tvs[i][5].setText(tmpActivity);
				tvs[i][5].setTextSize(12);
				tvs[i][5].setWidth(130);
				tvs[i][5].setHeight(120);
				//tvs[i][5].setBackgroundColor(Color.YELLOW);
				tvs[i][5].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][5].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][5]);

				tvs[i][0] = new TextView(this);
				tvs[i][0].setTag("id" + i);// setting tag with index i
				tvs[i][0].setText(bkk.getId());
				tvs[i][0].setWidth(0);
				tvs[i][0].setHeight(0);
				tvs[i][0].setTextSize(0);
				
				//tvs[i][0].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][0].setVisibility(View.INVISIBLE);
				// rg.addView(rds[i]);
				tbrs[i].addView(tvs[i][0]);

				tbrs[i].setGravity(Gravity.CENTER_HORIZONTAL);

				tbl.addView(tbrs[i]);

			}
			tbrs[count] = new TableRow(this);
			tbrs[count].setBackgroundResource(R.color.color_deep_blue);
			TextView emptytvs;
			emptytvs = new TextView(this);

			emptytvs = new TextView(this);
			emptytvs.setTag("empty");// setting tag with index i
			emptytvs.setText("");
			emptytvs.setTextSize(10);
			emptytvs.setWidth(100);
			emptytvs.setHeight(30);
			emptytvs.setGravity(Gravity.CENTER);
			tbrs[count].addView(emptytvs);
			tbl.addView(tbrs[count]);
		} else {
			//DialogHelper
			//		.getOkAlertDialog(this, "No record has been found.", "")
			//		.show();
			
			YesAction yesAction = new YesAction() {
				public void fnDoYesAction() {
					finish();
				}
			};
			
			DialogHelper
			.getOkActionDialog(
					cancelActivity,
					"Cancel Booking",
					"No record has been found.",
					yesAction)
			.show();
		}

	}

	private void fnLoadCancelBookData() {
		//remove old table rows for resume()
		removetbr();
		
		final CancelBookingActivity cbActivity = this;
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object resultList) {
				Log.d(TAG, "onTaskCompleted, bookings:" + resultList.toString());
				List<Booking> bookingList = (List<Booking>) resultList;
				cbActivity.fnSetCancelBooking(bookingList);
			}

			public void onTaskFailed(String errMessage) {
				Log.e(TAG, errMessage);
				Toast.makeText(cbActivity,
						"Error loading booking...\n" + errMessage,
						Toast.LENGTH_LONG).show();
			}
		};
		CancelBookingPageTask cbTask = new CancelBookingPageTask(this,
				completeAction);
		cbTask.fnGetCancelBookingList();
	}

	public void removetbr() {

		// remove table rows for reload
		TableLayout tbl = (TableLayout) findViewById(R.id.cancel_booking_table);
		int count = tbl.getChildCount();
		for (int i = 1; i < count; i++) {
			View child = tbl.getChildAt(i);
			if (child instanceof TableRow)
				((ViewGroup) child).removeAllViews();
		}
	}

	/*
	 * public void reload() {
	 * 
	 * // reload this activity Intent intent = getIntent();
	 * overridePendingTransition(0, 0);
	 * intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); finish();
	 * overridePendingTransition(0, 0); startActivity(intent);
	 * 
	 * }
	 */
	public void fnfailtocancel() {
		// show dialog if fail to cancel
		DialogHelper.getOkAlertDialog(this, "Fail to cancel booking.", "")
				.show();
	}
	public void fnaddactivitytodb(Booking bkdetail){

		DatabaseHelper db = new DatabaseHelper(this);

		/**
		 * CRUD Operations
		 * */
		// Inserting activity
		Log.d("Insert: ", "Inserting ..");
		db.addActivity(new Booking(bkdetail.getActivity(),bkdetail.getBkType(), bkdetail.getCentre(),
				bkdetail.getCourt(), bkdetail.getDate(), bkdetail.getTime(), bkdetail.getalarmId()));
	}
	

	
	public void fngofacebook(final Booking bkdetail){
		
		YesAction yesAction = new YesAction() {
			public void fnDoYesAction() {

				Context ctx = getBaseContext();
				Intent i = new Intent(ctx, FacebookActivity.class);

				i.putExtra("bookObj", bkdetail);
				startActivity(i);

				//Context ctx = getBaseContext();
				//Intent intent7 = new Intent(ctx,
				//		FacebookActivity.class);

				//intent7.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//ctx.startActivity(intent7);
			}
		};
		
		// alert box share box
		DialogHelper
				.getYesNoDialog(
						this,
						"Share Booking",
						"Share this action on FACEBOOK?",
						yesAction)
				.show();
		
	}
	
	

	public void fnaddtesttodbandalarm(){
		
		Log.d("Alarm Service", "asfasdfasdf");
		//seting tmp bkdetail data
		Booking bkdetail = new Booking();
		bkdetail.setActivity("Table tennis");
		bkdetail.setBkType("Booking Made");
		bkdetail.setCentre("SHAWSPORTS");
		bkdetail.setCourt("TT1");
		bkdetail.setDate("01-Mar-2013");
		bkdetail.setTime("01:08-09:29");
		
		int randomNumber = (int) (new Date().getTime());				
		
		String splitdate[] = bkdetail.getDate().split("-"); 
		
		
		Date date = null;
		try {
			date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(splitdate[1]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    Calendar cals = Calendar.getInstance();
	    cals.setTime(date);
	    int month = cals.get(Calendar.MONTH);
		
		
		Calendar cal = Calendar.getInstance(); // for using this you need to
												// import java.util.Calendar;

		// add minutes to the calendar object
		cal.set(Calendar.MONTH, month); //0=Jan 1=Feb 2=Mar etc.....
		cal.set(Calendar.YEAR, Integer.parseInt(splitdate[2]));
		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(splitdate[0]));
		cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(bkdetail.getTime().substring(0, 2)));
		cal.set(Calendar.MINUTE, Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		cal.add(Calendar.MINUTE, -5);

		int alarmservice_Id = randomNumber;
		
		Log.d("Setting Alarm Service",  "Alarm ID: "+ alarmservice_Id + "---------" + Integer.parseInt(splitdate[0]) + "-" + month + "-" + Integer.parseInt(splitdate[2]) + " Time:" + Integer.parseInt(bkdetail.getTime().substring(0, 2)) + ":" + Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		//cal.add(Calendar.SECOND, 5);     

		Intent alarmintent = new Intent(getApplicationContext(),
				AlarmReceiver.class);
		alarmintent.putExtra("title", "Polyu Sport Facilities Booking System");
		alarmintent.putExtra("note", bkdetail.getActivity() + " Notification");

		
		PendingIntent sender = PendingIntent.getBroadcast(
				getApplicationContext(), alarmservice_Id, alarmintent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

		
		//PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) alarm_id, alarmintent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		
		
		DatabaseHelper db = new DatabaseHelper(this);

		/**
		 * CRUD Operations
		 * */
		// Inserting activity 
		Log.d("Insert: ", "Inserting ..");
		db.addActivity(new Booking(bkdetail.getActivity(),bkdetail.getBkType(), bkdetail.getCentre(),
				bkdetail.getCourt(), bkdetail.getDate(), bkdetail.getTime(), alarmservice_Id));
	}
	

	public void fnRemoveBKfromAlarm(Booking bkdetail){



		Booking dbbkdetail = new Booking();
		DatabaseHelper db = new DatabaseHelper(this);
		dbbkdetail = db.getActivitybyDateTime(bkdetail.getDate(),bkdetail.getTime());
		Intent alarmintent = new Intent(this.getApplicationContext(),
				AlarmReceiver.class);

        AlarmManager am = (AlarmManager) this.getApplicationContext().getSystemService(Context.ALARM_SERVICE);

		Log.d("remove alarm service: ",  ""+dbbkdetail.getalarmId());
		

		
		PendingIntent sender = PendingIntent.getBroadcast(
				this.getApplicationContext(), dbbkdetail.getalarmId(), alarmintent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
		

		am.cancel(sender);		
		
	}
}
